package com.fingard.dsp.bank.directbank.nnbill01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.SendBankRespose;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.nnbill01.md5.MD5Util;
import com.fingard.dsp.bank.directbank.nnbill01.wsdl.gateway.GatewayOrderQueryServiceLocator;
import com.fingard.dsp.bank.directbank.nnbill01.wsdl.gateway.dto.GatewayOrderDetail;
import com.fingard.dsp.bank.directbank.nnbill01.wsdl.gateway.dto.GatewayOrderQueryRequest;
import com.fingard.dsp.bank.directbank.nnbill01.wsdl.gateway.dto.GatewayOrderQueryResponse;
import com.fingard.dsp.bank.reqrespobj.statement.RefundState;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.ZipHelper;
import com.fingard.xml.XmlTextReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.*;

/**
 * 快钱对账单获取
 * 
 * @author Cruise
 * @date 2019/4/15
 */
public class NNBill01Statement extends NNBill01Base implements IStatement {
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();

		// 获取日交易确认明细对账单
		String[] singlePayRecRespHeader = getAccountStatement(p_reqQrySttm, retAts);
		String singlePayRecTotalNum = retAts.totalNum;
		WriteBankLogLn("单笔总笔数:" + singlePayRecTotalNum);
		if (singlePayRecTotalNum.length() == 0) {
			singlePayRecTotalNum = "0";
		}
		
		// 获取POS对账单
		String[] tmpPosRecRespHeader = getPosRecStatement(p_reqQrySttm, retAts);
        String tmpPosRecTotalNum = retAts.totalNum;
        WriteBankLogLn("POS对账单总笔数:" + tmpPosRecTotalNum);
        if (tmpPosRecTotalNum.length() == 0) {
        	tmpPosRecTotalNum = "0";
		}
		
		// 获取无线POS对账单
		String[] wirelessPosRespHeader = getWirelessPOS(p_reqQrySttm, retAts);
		String wirelessPosTotalNum = retAts.totalNum;
		WriteBankLogLn("无线POS对账单总笔数:" + wirelessPosTotalNum);
		if (wirelessPosTotalNum.length() == 0) {
			wirelessPosTotalNum = "0";
		}
		
		// 获取人民币网关对账单
		String[] gatewayRespHeader = getGatewayStatement(p_reqQrySttm, retAts);
		String gatewayTotalNum = retAts.totalNum;
		WriteBankLogLn("人民币网关对账单总笔数:" + gatewayTotalNum);
		if (gatewayTotalNum.length() == 0) {
			gatewayTotalNum = "0";
		}
		
		String[] batchRespHeader = getBatchStatement(p_reqQrySttm, retAts);
		String batchTotalNum = retAts.totalNum;
		WriteBankLogLn("批量代收付对账单总笔数:" + batchTotalNum);
		if (batchTotalNum.length() == 0) {
			batchTotalNum = "0";
		}
		
		if (singlePayRecRespHeader[0].equals("-1") && wirelessPosRespHeader[0].equals("-1") && gatewayRespHeader[0].equals("-1") && batchRespHeader[0].equals("-1") && "-1".equals(tmpPosRecRespHeader[0])) {
			String respInfo = singlePayRecRespHeader[1];
			if (StringHelper.isNullOrEmpty(respInfo)) {
				respInfo = wirelessPosRespHeader[1];
			}
			if (StringHelper.isNullOrEmpty(respInfo)) {
				respInfo = gatewayRespHeader[1];
			}
			if (StringHelper.isNullOrEmpty(respInfo)) {
				respInfo = batchRespHeader[1];
			}
			if (StringHelper.isNullOrEmpty(respInfo)) {
				respInfo = tmpPosRecRespHeader[1];
			}
			
			retAts.writeRespCode("-1");
        	retAts.writeRespInfo(respInfo);
		} else {
			if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");
				
				String respInfo = singlePayRecRespHeader[1];
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = wirelessPosRespHeader[1];
				}
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = gatewayRespHeader[1];
				}
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = tmpPosRecRespHeader[1];
				}
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = "交易为空";
				}
				retAts.writeRespInfo(respInfo);
			}
			
			int totalNum = Integer.parseInt(singlePayRecTotalNum) + Integer.parseInt(wirelessPosTotalNum) + Integer.parseInt(gatewayTotalNum) + Integer.parseInt(batchTotalNum) + Integer.parseInt(tmpPosRecTotalNum);
			retAts.isWritedTotalNum(String.valueOf(totalNum));
		}
		
		retAts.writeEnd();
		return retAts;
	}

	private String[] getAccountStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "*");
			if (actItem != null) {
				StringBuilder sbXml = new StringBuilder();

				sbXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
				sbXml.append("<MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\">");
				sbXml.append("<version>1.0</version>");
				sbXml.append("<QryConfirmListContent>");
				sbXml.append("<txnDate>" + p_reqQrySttm.busDate + "</txnDate>");
				sbXml.append("<merchantId>" + actItem.merchantId + "</merchantId>");
				sbXml.append("</QryConfirmListContent>");
				sbXml.append("</MasMessage>");

				String queryUrl = bankFront.getUrl("querylist");
				this.WriteBankLogLn("对账单查询提交地址：" + queryUrl);

				String reqXml = sbXml.toString();
				this.WriteBankLogStep2(reqXml);

				// 发快钱
				SendBankRespose smsResp = SmsPost.sendPost(queryUrl, actItem, reqXml, getCharset());

				WriteBankLogStep3(smsResp);

				// 解析快钱返回数据
				if (smsResp.connState == "") {
					if (smsResp.retMessage.indexOf("<!DOCTYPE html>") > 0) {
						respCode = "-1";
						respInfo = "商户证书配置出错，请检查相应证书配置";
					} else {
						StringBuilder tmpSbMsg = new StringBuilder();
						XmlTextReader tmpBkReader = loadBankRespXmlReader(smsResp.retMessage, tmpSbMsg);

						if (smsResp.retMessage.indexOf("<") >= 0) {
							totalNum = Integer.parseInt(tmpBkReader.getFirstText("/MasMessage/QryConfirmListContent/TxnListCount"));

							/*
							 * 如果"<TxnListContent></TxnListContent>"节点不存在,表示指定日期未发生交易或者未在请求日期之后生成交易记录
							 */
							String detailContent = tmpBkReader.getFirstText("/MasMessage/QryConfirmListContent/TxnListContent");
							if (detailContent != null) {
								while (tmpBkReader.read("/MasMessage/QryConfirmListContent/TxnListContent/Txn")) {
									RetAtsStatementDetail p_retDetail = new RetAtsStatementDetail();

									String amount = tmpBkReader.readedXElement.getSingleText("amount");
									String fee = tmpBkReader.readedXElement.getSingleText("fee");
									
									p_retDetail.askNumber = tmpBkReader.readedXElement.getSingleText("externalRefNumber");
									p_retDetail.busTime = tmpBkReader.readedXElement.getSingleText("transTime");
									p_retDetail.amount = Format.DecimalAmtFormat.format(Double.parseDouble(amount));
									p_retDetail.fee = Format.DecimalAmtFormat.format(Double.parseDouble(fee));
									p_retDetail.transState = TransState.Success;
									
									retAts.writeRetDetail(p_retDetail);
								}
							} else {
								respCode = "-1";
								respInfo = "尚未生成交易明细";
							}
						} else {
							respCode = "-1";
							respInfo = tmpSbMsg.toString();
						}
					}
				} else {
					respCode = "-1";
					respInfo = smsResp.retMessage;
				}
			} else {
				respHeader[0] = "-1";
				respHeader[1] = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}

	private String[] getWirelessPOS(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		
		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "");
			if (actItem != null) {
				// FTP服务器配置信息
				String ftpHost = getBankConfig().getMapValueByKey("ftpMapping", "ftpHost");
				int ftpPort = Integer.parseInt(getBankConfig().getMapValueByKey("ftpMapping", "ftpPort"));

				// FTP登录用户信息
				String ftpUserName = getBankConfig().getMapValueByKey("ftpMapping", "ftpUserName");
				String ftpPassword = getBankConfig().getMapValueByKey("ftpMapping", "ftpPassword");

				// 对账单文件所在目录
				String ftpPath = getBankConfig().getMapValueByKey("ftpMapping", "ftpPath");

				// 本地路径
				String localPath = getBankConfig().getMapValueByKey("ftpMapping", "localPath");
				String fileName = actItem.merchantId + "_" + Format.Date8Format.format(p_reqQrySttm.getBusDate()) + ".txt";

				// 从FTP下载对账单
				FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);

				// 从本地文件读取对账单数据
				String filePath = localPath + File.separator + fileName;
				String ftpFileContent = FtpUtil.getTextFromFile(filePath, getCharset());

				if (ftpFileContent.equals("")) {
					respCode = "-1";
					respInfo = "读取对账单文件失败!";
				}

				// 返回对账单文件数据
				WriteBankLogStep3(ftpFileContent);

				// 解析快钱无线POS对账单
				String[] totalLine = ftpFileContent.split("\r\n");
				if (totalLine.length > 1) {
					respCode = "0";
					respInfo = "";

					// 汇总信息
					int endIndex = totalLine[0].lastIndexOf("总金额");
					totalNum = Integer.parseInt(totalLine[0].substring(4, endIndex).trim());

					// 获取对账单详细内容
					int detailIndex = ftpFileContent.indexOf("流水号");
					String detailContent = ftpFileContent.substring(detailIndex);

					StringReader strReader = new StringReader(detailContent);
					BufferedReader tmpReader = new BufferedReader(strReader);

					// 获取列名信息
					tmpReader.readLine();
					String[] columns = new String[] { "流水号", "终端号", "交易识别号", "交易日期", "金额", "清算账号", "交易类型" };

					/*
					 * 获取明细数据
					 */
					String line = "";
					while ((line = tmpReader.readLine()) != null) {
						// 每行明细内容
						String eachline = line.trim();
						if (eachline == null) {
							retAts.writeRespCode("-1");
							retAts.writeRespInfo("本日或本月无收支");

							break;
						} else {
							if (eachline.equals("")) {
								continue;
							}

							String[] values = eachline.split("\\|");
							if (columns.length == values.length) {
								HashMap<String, String> mapKV = SplitHelper.splitAsValueMap(columns, values);
								RetAtsStatementDetail retDetail = new RetAtsStatementDetail();

								if (mapKV.containsKey("交易日期")) {
									retDetail.busTime = mapKV.get("交易日期").trim() + "000000";
								}

								if (mapKV.containsKey("交易类型")) {
									retDetail.busType = mapKV.get("交易类型").trim();
								}

								if (mapKV.containsKey("流水号")) {
									retDetail.askNumber = mapKV.get("流水号").trim();
								}

								if (mapKV.containsKey("金额")) {
									retDetail.amount = mapKV.get("金额").trim();
								}

								if (mapKV.containsKey("终端号")) {
									retDetail.termCode = mapKV.get("终端号").trim();
								}

								retDetail.transState = TransState.Success;
								retDetail.refundState = RefundState.Exception;

								retAts.writeRetDetail(retDetail);
							} else {
								break;
							}
						}
					}
				} else {
					respCode = "-1";
					respInfo = "返回结果不符合预期!";
				}
			} else {
				respHeader[0] = "-1";
				respHeader[1] = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}
	
	private String[] getGatewayStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		
		String respCode = "";
		String respInfo = "";
		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "*");
			if (actItem != null) {
				// 拼快钱请求数据
				LinkedHashMap<String,String> params = new LinkedHashMap<String,String>();
				
				Date date = Format.Date8Format.parse(p_reqQrySttm.busDate);
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				cal.add(Calendar.DATE, 1);
				
				params.put("inputCharset", "1");
				params.put("version", "v2.0");
				params.put("signType", "1");
				params.put("merchantAcctId", actItem.merchantId);
				params.put("queryType", "1");
				params.put("queryMode", "1");
				params.put("startTime", Format.DateTime14Format.format(p_reqQrySttm.getBusDate()));
				params.put("endTime", Format.DateTime14Format.format(cal.getTime()));
				params.put("requestPage", "");
				params.put("orderId", "");
				params.put("key", actItem.saltKey);
				
				String signMsgParam = convertMapToStr(params);
				WriteBankLogLn("加签原始数据：" + signMsgParam);
				String signMsg = MD5Util.md5Hex(signMsgParam.getBytes(getCharset())).toUpperCase();
				params.put("signMsg", signMsg);
				GatewayOrderQueryRequest queryRequest = new GatewayOrderQueryRequest();
				
				queryRequest.setInputCharset(params.get("inputCharset"));
				queryRequest.setVersion(params.get("version"));
				queryRequest.setSignType(Integer.parseInt(params.get("signType")));
				queryRequest.setMerchantAcctId(params.get("merchantAcctId"));
				queryRequest.setQueryType(Integer.parseInt(params.get("queryType")));
				queryRequest.setQueryMode(Integer.parseInt(params.get("queryMode")));
				queryRequest.setOrderId(params.get("orderId"));
				queryRequest.setStartTime(params.get("startTime"));
				queryRequest.setEndTime(params.get("endTime"));
				queryRequest.setRequestPage(params.get("requestPage"));
				queryRequest.setSignMsg(params.get("signMsg"));

				String sendRUL = bankFront.getUrl("queryGW");
				WriteBankLogLn2("人民币网关支付对账单查询服务地址为:" + sendRUL);
				String req = signMsgParam + "&signMsg" + signMsg;
				WriteBankLogStep2(req);
				GatewayOrderQueryServiceLocator locator = new GatewayOrderQueryServiceLocator(sendRUL);
				GatewayOrderQueryResponse queryResponse = locator.getgatewayOrderQuery().gatewayOrderQuery(queryRequest);
				
				// 解析快钱返回数据
				String errCode = queryResponse.getErrCode();
				WriteBankLogStep3(queryResponse.toString());

				if (errCode != null && !"".equals(errCode)) {
					respCode = "0";
					respInfo = queryResponse.getErrCode();
				} else {
					GatewayOrderDetail[] orders = queryResponse.getOrders();
					totalNum = orders.length;
					
					for (int i = 0; i < orders.length; i++) {
						GatewayOrderDetail detail = orders[i];
						
						RetAtsStatementDetail p_retDetail = new RetAtsStatementDetail();

						p_retDetail.askNumber = detail.getOrderId();
						p_retDetail.busTime = detail.getDealTime();
						p_retDetail.amount = StringHelper.amountDivide100(Long.toString(detail.getOrderAmount()));
						p_retDetail.fee = StringHelper.amountDivide100(Long.toString(detail.getFee()));
						
						String transtate = detail.getPayResult();
						if ("10".equals(transtate)) {
							p_retDetail.transState = TransState.Success;
						}
						
						retAts.writeRetDetail(p_retDetail);
					}
				}
			} else {
				respHeader[0] = "-1";
				respHeader[1] = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}

	private String[] getBatchStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
		String[] respHeader = new String[]{"",""};
		String respCode = "";
		String respInfo = "";
		
		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_reqQrySttm.actNum, "", "", "bat");
			if (actItem != null) {
				FtpSet ftpSet = bankFront.getFtpSet("statement");
				String statementFile = "99bill_" + actItem.merchantId + "_" + Format.Date10Format.format(p_reqQrySttm.getBusDate());
	            String downFilePath = ftpSet.downDir + "/" + statementFile + ".zip";
	            String localSavePath = getTempFileDirectory() + File.separator + statementFile + ".zip";
	            
	            WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
	            WriteBankLogLn("开始下载服务器文件" + downFilePath + "至本地文件" + localSavePath);
				FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
	    		FtpReceiver tmpReceiver = ftpPtClient.downloadFile(downFilePath, localSavePath);
	    		ftpPtClient.disconnect();
	    		if(tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
	                WriteBankLogLn2("解压至：" + getTempFileDirectory() + File.separator + statementFile + "目录下");
	                ZipHelper.unzipFile(localSavePath, getTempFileDirectory());
	                
	                String fileContent = readExcel(getTempFileDirectory() + File.separator + statementFile + File.separator + statementFile + ".xls");
	                WriteBankLogLn2("对账单重组后响应内容为:\r\n" + fileContent);
	                
	                String[] totalLine = fileContent.split("\r\n");
	                totalNum = totalLine.length;
	                
	                for (String eachline : totalLine) {
	                	String[] eachNode = eachline.split(",");
	                	RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

	                	tmpRetDetail.askNumber = eachNode[12];
	                	tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTimeFormat.parse(eachNode[0]));
	                	
	                	tmpRetDetail.memo = eachNode[13];
	                	tmpRetDetail.channelOrderNo = eachNode[1];
	                	
	                	String transAmt = eachNode[7];
	                	if (StringHelper.isNullOrEmpty(transAmt)) {
	                		transAmt = eachNode[10];
	                	}
	                	if (transAmt.contains(",")) {
	                		transAmt = transAmt.replace(",", "");
	                	}
	                	tmpRetDetail.amount = Format.DecimalAmtFormat.format(Double.parseDouble(transAmt));
	                	
	                	String fee = eachNode[6];
	                	if (StringHelper.isNullOrEmpty(fee)) {
	                		fee = eachNode[9];
	                	}
	                	tmpRetDetail.fee = Format.DecimalAmtFormat.format(Double.parseDouble(fee));
						
	                	String busTypeStatus = getBankConfig().getMapKeyByValue("busTypeStatusMapping", eachNode[2]);
	                	boolean useNewBusType = getBankConfig().getValueAsBool("useNewBusType");
	                	if (useNewBusType) {
	                		tmpRetDetail.busType = busTypeStatus;
	                	}
	                	
	                	String cdFlag = eachNode[7];
	                	if (StringHelper.isNullOrEmpty(cdFlag)) {
	                		tmpRetDetail.cdFlag = "1";
	                	} else {
	                		tmpRetDetail.cdFlag = "2";
	                	}
	                	
	                	if (StringHelper.isNullOrEmpty(busTypeStatus)) {
	                		tmpRetDetail.transState = TransState.Exception;
	                	} else if ("0".equals(busTypeStatus)) {
	                		tmpRetDetail.transState = TransState.Success;
	                		tmpRetDetail.refundState = RefundState.RefundSuccess;
	                	} else if ("1".equals(busTypeStatus)) {
	                		tmpRetDetail.transState = TransState.RefundTicket;
	                	} else {
	                		tmpRetDetail.transState = TransState.Success;
	                	}
	                	
						retAts.writeRetDetail(tmpRetDetail);
	                }
	    		} else {
	    			respCode = "-1";
	    			respInfo = tmpReceiver.connMsg;
	    		}
			} else {
				respHeader[0] = "-1";
				respHeader[1] = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			respCode = "-1";
			respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.totalNum = String.valueOf(totalNum);
		respHeader[0] = respCode;
		respHeader[1] = respInfo;
		return respHeader;
	}

	/**
     * POS对账单
     * 
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */
    private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};
        
        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        retAts.totalNum = "0";
        int totalNum = 0;
        
        try {
        	if (StringHelper.isNullOrEmpty(p_reqQrySttm.channel)) {
        		ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "pos01");
    			if (actItem == null) {
    				respHeader[0] = "-1";
    				respHeader[1] = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息";
    				return respHeader;
    			}
        	}
        	
            FtpSet ftpSet = bankFront.getFtpSet("pos");
            ftpSet.downDir = StringHelper.trimEnd(ftpSet.getDownDir("pos"), "/") + "/" + p_reqQrySttm.busDate;
            WriteBankLogLn2("快钱POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);

            StringBuilder sbFileContent = new StringBuilder();
            
            String tmpPosMode = getBankConfig().getValueAsString("posRecUseVersion");
            if ("B".equals(tmpPosMode)) {
            	String downFileName = p_reqQrySttm.actNum + p_reqQrySttm.busDate + ".txt";
                WriteBankLogLn2("快钱POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

                String localFilePath = createTempFileDirectory() + File.separator + downFileName;
                WriteBankLogLn2("快钱POS对账单保存本地路径:" + localFilePath);

                FtpReceiver ftpReceiver = null;
    			String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
    			if ("ftp".equals(posRecRequestType.toLowerCase())) {
    				FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
    	            ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
    			} else if ("sftp".equals(posRecRequestType.toLowerCase())) {
    				SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
    				String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
    				WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
    				ftpReceiver = sftpPortClient.downloadFile("",sftpFilePath, localFilePath);
    			}
                if (ftpReceiver.isCompleted) {
                    if (sbFileContent.length() > 0) {
                        sbFileContent.append("\n");
                    }
                    sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = "快钱POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                }
            } else {
            	tmpRespCode = "-1";
                tmpRespInfo = "对账单版本错误,当前版本为:[" + tmpPosMode + "].";
            }
            if (StringHelper.hasAnyChar(sbFileContent.toString())) {
            	tmpRespCode = "0";
            	
                String tmpStrRet = sbFileContent.toString();
                WriteBankLogLn2("快钱POS对账单响应数据:\r\n" + tmpStrRet);

                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null) {
                        break;
                    }
                    if ("".equals(eachline.trim())) {
                        continue;
                    }
                    String[] detailNodes = eachline.split("`~");
                    if (p_reqQrySttm.actNum.equals(detailNodes[1].trim())) {
                        totalNum++;
                        isContinue = true;
                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                        if (StringHelper.hasAnyChar(detailNodes[4])) {
                            tmpRetDetail.askNumber = detailNodes[4].trim();
                        }

                        tmpRetDetail.cdFlag = "22";

                        if (StringHelper.hasAnyChar(detailNodes[11])) {
                            tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[11].trim());
                        }

                        if (StringHelper.hasAnyChar(detailNodes[15])) {
                            tmpRetDetail.fee = StringHelper.amountDivide100(detailNodes[15].trim());
                        }

                        tmpRetDetail.busTime = detailNodes[6];

                        if (StringHelper.hasAnyChar(detailNodes[7])) {
                            tmpRetDetail.oppAct = detailNodes[7].trim();
                        }

                        if (StringHelper.hasAnyChar(detailNodes[8])) {
                            tmpRetDetail.oppActName = detailNodes[8].trim();
                        }

                        if ("2".equals(detailNodes[13].trim())) {
                            tmpRetDetail.transState = TransState.Success;
                        } else {
                            tmpRetDetail.transState = TransState.Fail;
                        }

                        retAts.writeRetDetail(tmpRetDetail);
                    }
                }

                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }
}
